package com.linkage.jz.bankruptcy.activity.Person;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public  class PersonSettingNickNameActivity extends BaseWhiteActivity implements OnClickListener{
    private static final String TAG = PersonSettingNickNameActivity.class.getSimpleName();

    private ShapeLoadingDialog shapeLoadingDialog ;


    TextView btn_save;
    EditText et_nickname;
    private static String mNickname;

    public static void start(Context context,String nickname) {
        mNickname = nickname;
        Intent intent = new Intent(context, PersonSettingNickNameActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_setting_setnickname, "修改昵称");
        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        btn_save = findViewById(R.id.btn_save);
        et_nickname = findViewById(R.id.et_nickname);
        et_nickname.setText(mNickname);
        btn_save.setOnClickListener(this);
        showSave();
        et_nickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    private void showSave()
    {
        String str1 =  et_nickname.getText().toString().trim();


        if(!str1.equalsIgnoreCase("") )
        {

            btn_save.setClickable(true);
            btn_save.setBackgroundResource((R.drawable.login_corner_btn));
        }else{
            btn_save.setClickable(false);
            btn_save.setBackgroundResource((R.drawable.login_corner_nosel_btn));
        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_save:
                String nickname = et_nickname.getText().toString();

                if("".equalsIgnoreCase(nickname))
                {
                    showToast("昵称不能为空");
                    return;
                }

                SaveData(nickname);
                break;
            case R.id.top_back:
                finish();
                break;

            default:
                break;
        }
    }

    public void SaveData(final String nickname)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("avatar", "")
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("userId", userId)
                .add("userToken",userToken)
                .add("username", nickname)
                .add("email", "")
                .add("company", "")
                .add("type", "2")
                .build();

        String url = Consts.WEBURL_MODIFYPERSON;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        showToast("保存失败");
                    }

                });
                }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("保存成功", ToastUtil.TOAST_TYPE.SUCCESS);
                                BankruptcyApp.loginInfo.setUsername(nickname);
                            }

                        });
                        finish();

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("保存失败");
                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            showToast("保存失败");
                        }

                    });
                }
            }
        });
    }


}

